<!--新增用户-->
<template>
  <el-dialog
    class="base-dialog"
    :class="{ readonly: readOnly }"
    :custom-class="'panna-dialog_small'"
    :title="title"
    :visible.sync="dialogVisible"
    :append-to-body="true"
    :before-close="handleClose"
    @closed="closedDialog"
  >
    <p slot="title">{{ title }}</p>

    <el-form
      ref="formData"
      v-loading="formLoading"
      :rules="formRules"
      :model="formData"
      :label-width="$i18n.locale === 'en' ? '150px' : '100px'"
    >
      <el-form-item :label="dataList.GroupName" prop="name">
        <el-input
          v-model="formData.name"
          :disabled="readOnly"
          :placeholder="dataList.EnterGroupName"
        />
      </el-form-item>
      <el-form-item :label="dataList.eGroupName" prop="eName">
        <el-input
          v-model="formData.eName"
          :disabled="readOnly"
          :placeholder="dataList.EnterGroupName"
        />
      </el-form-item>

      <el-form-item :label="dataList.GroupMembers" prop="groupUserIds">
        <el-select
          v-model="formData.groupUserIds"
          :disabled="readOnly"
          multiple
          :placeholder="dataList.EnterGroupMembers"
          filterable
          remote
          reserve-keyword
          :remote-method="remoteGroup"
          :loading="searchUserLoading"
        >
          <el-option
            v-for="item in groupList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item :label="dataList.Remark" prop="remark">
        <el-input
          v-model="formData.remark"
          type="textarea"
          :disabled="readOnly"
          maxlength="50"
          show-word-limit
        />
      </el-form-item>
      <el-form-item :label="dataList.status" :disabled="readOnly" prop="status">
        <el-switch
          v-model="formData.status"
          :disabled="readOnly"
          :active-value="1"
          :inactive-value="0"
        />
      </el-form-item>
    </el-form>

    <span v-if="!readOnly" slot="footer" class="base-dialog-footer">
      <el-button
        v-loading="submitLoad"
        :disabled="submitLoad"
        type="primary"
        @click="submitForm"
        >{{ btn.Save }}</el-button
      >
      <el-button @click="handleClose">{{ btn.Cancel }}</el-button>
    </span>
  </el-dialog>
</template>

<script>
import {
  getInfo,
  Update,
  Create,
} from "../../../api/Permission/PermissionUserGroup.js";
import { getUserListNoPage } from "../../../api/Permission/PermissionUser.js";
import { getGroupUserList } from "../../../api/Permission/PermissionGroupUser.js";
export default {
  name: "PermissionUserGroupDialog",
  props: {
    value: {
      type: Boolean,
      default: false,
    },
    readOnly: {
      type: Boolean,
      default: false,
    },
    editId: {
      type: [String, Number],
      default: "",
    },
  },
  data() {
    return {
      title: "",
      dialogVisible: false,
      submitLoad: false,
      formData: {
        name: "",
        eName: "",
        status: 1,
        remark: "",
        groupUserIds: [],
      },
      formRules: {
        name: [
          {
            required: true,
            message: this.$t("Permission.PermissionUser.EnterGroupName"),
          },
        ],
        eName: [
          {
            required: true,
            message: this.$t("Permission.PermissionUser.EnterGroupName"),
          },
        ],
        groupUserIds: [
          {
            type: "array",
            required: true,
            message: this.$t("Permission.PermissionUser.EnterGroupMembers"),
          },
        ],
      },
      userList: [],
      groupList: [],
      searchUserLoading: false,
      formLoading: false,
    };
  },
  computed: {
    btn() {
      return this.$t("Permission.buttons");
    },
    dataList() {
      return this.$t("Permission.PermissionUser");
    },
  },
  watch: {
    value: function() {
      this.dialogVisible = this.value;
      if (this.value) {
        this.init();
      }
    },
  },
  methods: {
    // 初始化
    async init() {
      // 获取人员列表 每次打开获取 防止数据不是最新
      this.formLoading = true;
      const userListData = await this.getUser().catch(() => {
        this.formLoading = false;
      });
      this.userList = userListData;
      this.groupList = userListData;
      // editId 存在表示编辑 不存在表示新增
      this.title = this.readOnly
        ? this.$t("Permission.buttons.Look")
        : this.editId
          ? this.$t("Permission.buttons.Edit")
          : this.$t("Permission.buttons.Add");

      // 编辑用户 先获取用户信息
      if (this.editId) {
        // 获取用户信息
        getInfo({ id: this.editId })
          .then((res) => {
            getGroupUserList({
              userGroupId: this.editId,
              pageIndex: 1,
              pageSize: 9999,
            }).then((group) => {
              if (group.data.dataList != null) {
                group.data.dataList.forEach((v) => {
                  v.id = v.userId;
                  if (
                    this.groupList.filter((l) => l.id === v.id).length === 0
                  ) {
                    this.groupList.push(v);
                  }
                });
              }
              this.formLoading = false;
              const { name, status, remark } = res.data;
              this.formData = {
                name,
                status,
                remark,

                groupUserIds:
                  group.data.dataList == null
                    ? []
                    : group.data.dataList.map((v) => v.id),
              };
            });
          })
          .catch(() => {
            this.formLoading = false;
          });
      } else {
        this.formLoading = false;
      }
    },
    // 提交表单
    submitForm() {
      // 校验表单必填项
      this.$refs.formData.validate((valid) => {
        if (valid) {
          this.submitLoad = true;
          // 当前编辑ID是否存在 存在则去更新用户信息
          const requestData = JSON.parse(JSON.stringify(this.formData));
          requestData.groupUserIds = requestData.groupUserIds.join(",");
          if (this.editId) {
            this.editAPI(requestData);
          } else {
            // 新增
            this.addAPI(requestData);
          }
        } else {
          this.$message.error(this.$t("Permission.buttons.PleaseComplete"));
        }
      });
    },
    // 新增接口
    addAPI(data) {
      Create(data)
        .then((res) => {
          this.SuccessfulOperation();
        })
        .catch(() => {
          this.submitLoad = false;
        });
    },
    // 编辑接口
    editAPI(data) {
      Update({
        ...data,
        id: this.editId,
      })
        .then((res) => {
          this.SuccessfulOperation();
        })
        .catch(() => {
          this.submitLoad = false;
        });
    },
    // 操作成功回调用
    SuccessfulOperation() {
      this.submitLoad = false;
      // this.$message.success('操作成功');
      this.$emit("success");
      this.handleClose();
    },
    // 关闭弹框
    handleClose() {
      this.$emit("input", false);
    },
    // 关闭弹框动画结束
    closedDialog() {
      // 动画结束后在清空表单 防止页面闪烁
      this.$refs.formData.resetFields();
    },

    getUser(name = "") {
      return new Promise((resolve) => {
        getUserListNoPage({ name: name }).then((res) => {
          resolve(res.data);
        });
      });
    },

    // 搜索人员
    async remoteGroup(query) {
      this.searchUserLoading = true;
      const filter = await this.getUser(query);
      if (filter && filter.length) {
        this.groupList = filter;
      }
      this.searchUserLoading = false;
    },
  },
};
</script>

<style lang="scss" scoped>
.user-group-dialog {
  .el-dialog__body {
    padding-bottom: 24px;
  }
  .el-form {
    width: 500px;
    margin: 0 auto;
  }
  .relay-only-value {
    margin-bottom: 2px;
  }
  .default-form-item {
    display: block;
    height: 84px;
  }
}
.system-user-dialog {
  .el-dialog__body {
    padding: 24px 50px 0 20px;
  }
}
</style>
